<template>
  <div class="pt-24px">
    <!-- rules 校验的是 model 属性指定的对象 -->
    <n-form ref="formRef" :model="model" :rules="rules" size="large" :show-label="false">
      <!-- path 指定要校验的规则,如果此处设为 code, 则触发校验后，执行的是 code 规则 -->
      <n-form-item path="phone">
        <n-input v-model:value="model.phone" placeholder="手机号码" />
      </n-form-item>
      <n-form-item path="code">
        <n-input v-model:value="model.code" placeholder="验证码" />
        <div class="w-18px"></div>
        <n-button :disabled="isCounting" @click="handleSmsCode">{{ label }}</n-button>
      </n-form-item>
      <n-form-item path="pwd">
        <n-input v-model:value="model.pwd" type="password" placeholder="密码"></n-input>
      </n-form-item>
      <n-form-item path="confirmPwd">
        <n-input v-model:value="model.confirmPwd" type="password" placeholder="确认密码"></n-input>
      </n-form-item>
      <n-space :vertical="true" size="large">
        <n-checkbox v-model:checked="agreement">我已经仔细阅读并接受用户协议和隐私政策</n-checkbox>
        <n-button size="large" :block="true" type="primary" :round="true" @click="handleSubmit"
          >确定</n-button
        >
        <n-button size="large" :block="true" :round="true" @click="toLogin('pwd-login')">
          返回
        </n-button>
      </n-space>
    </n-form>
  </div>
</template>

<script setup lang="ts">
import { useSmsCode, useRouterChange } from '@/hooks'
import { FormInst, messageDark, useMessage } from 'naive-ui'
import { reactive, ref } from 'vue'

const model = reactive({
  phone: '',
  code: '',
  pwd: '',
  confirmPwd: '',
})
const rules = {
  phone: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入手机号',
  },
  code: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入验证码',
  },
  pwd: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
  },
  confirmPwd: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入确认默认',
  },
}
const formRef = ref<(HTMLElement & FormInst) | null>(null)
const { start, label, isCounting } = useSmsCode()
const { toLogin } = useRouterChange()
const message = useMessage()
const agreement = ref(false)

function handleSmsCode() {
  start()
}
function handleSubmit() {
  // validate 函数会触发 rules 中的所有规则
  // 若校验失败，将rule中的所有message将显示在对应位置
  formRef.value?.validate((errors) => {
    if (!errors) {
      message.success('验证成功')
    } else {
      message.error('验证失败')
    }
  })
}
</script>

<style scoped></style>
